<template>
  <view class="container">
    <scroll-view scroll-y class="form-scroll">
      <view v-for="(item, index) in fields" :key="index" class="form-item">
        <view class="label" v-if="item.__config__.showLabel&&item.type !== 'editor'&&item.type !== 'time'&&item.type !== 'timerange'&&item.type !== 'color'">{{ item.__config__.label }}</view>

        <!-- 单行文本 -->
        <input
          v-if="item.type === 'input'"
          v-model="form[item.__vModel__]"
          class="uni-input"
          :placeholder="item.placeholder"
        />

        <!-- 多行文本 -->
        <textarea
          v-else-if="item.type === 'textarea'"
          v-model="form[item.__vModel__]"
          class="uni-textarea"
          :placeholder="item.placeholder"
          auto-height
        ></textarea>

        <!-- 密码 -->
        <input
          v-else-if="item.type === 'password'"
          v-model="form[item.__vModel__]"
          :password="true"
          class="uni-input"
          :placeholder="item.placeholder"
        />
		<!-- 计数器 -->
		<view v-else-if="item.type === 'step'" class="uni-input-number">
		  <button
		    type="button"
		    class="btn-decrease"
		    @click="decreaseStep(item.__vModel__)"
		    :disabled="isStepMin(item.__vModel__)"
		  >-</button>
		  <input
		    type="number"
		    v-model="form[item.__vModel__]"
		    class="input-number"
		    @input="onStepInput(item.__vModel__,$event)"
		    :step="item.step || 1"
		    :min="item.min || 0"
		    :max="item.max || 999999"
		  />
		  <button
		    type="button"
		    class="btn-increase"
		    @click="increaseStep(item.__vModel__)"
		    :disabled="isStepMax(item.__vModel__)"
		  >+</button>
		</view>
		
		<!-- ✅ 富文本编辑器 -->
		  <editor
		    v-else-if="false"
		    :id="'editor-' + item.__vModel__"
		    :ref="'editor-' + item.__vModel__"
		    :placeholder="item.placeholder || '请输入内容'"
		    :style="{ height: (item.height || 300) + 'px' }"
		    :read-only="item.disabled"
		    @ready="onEditorReady($event, item.__vModel__)"
		    @input="onEditorInput($event, item.__vModel__)"
		    @focus="onEditorFocus"
		    @blur="onEditorBlur"
		    class="form-item-editor"
		  />

        <!-- 下拉选择 -->
        <uni-data-select
          v-else-if="item.type === 'select'"
          :localdata="item.__slot__.options"
          v-model="form[item.__vModel__]"
          :placeholder="item.placeholder || '请选择'"
          :disabled="item.disabled"
		  :clear="false"
          class="form-item-select"
        />

        <!-- 单选框 -->
        <view
          v-else-if="item.type === 'radio'"
          class="radio-group"
          :class="{ 'radio-group--horizontal': item.__config__.optionType === 'button' }"
          :key="form[item.__vModel__]">
        
          <!-- 单选框列表 -->
          <view class="radio-options">
            <label
              v-for="opt in item.__slot__.options"
              :key="opt.value"
              class="radio-item"
              :class="{
                'is-checked': form[item.__vModel__] === opt.value,
                'is-disabled': item.disabled || opt.disabled
              }"
              @tap="selectRadio(opt.value, item.__vModel__, item.disabled || opt.disabled)"
            >
              <!-- 圆形选中框 -->
              <view class="radio-icon">
                <view class="radio-inner"></view>
                <view
                  v-if="form[item.__vModel__] === opt.value"
                  class="radio-inner-checked"
                ></view>
              </view>
              <text class="radio-label">{{ opt.label }}</text>
            </label>
          </view>
        </view>

        <!-- 多选框 -->
        <!-- 多选框组 -->
        <view
          v-else-if="item.type === 'checkbox'"
          class="checkbox-group"
          :class="{ 'checkbox-group--horizontal': item.__config__.optionType === 'button' }"
          :key="form[item.__vModel__] ? form[item.__vModel__].join(',') : 'empty'"
        >
          <!-- 选项容器 -->
          <view class="checkbox-options">
            <label
              v-for="opt in item.__slot__.options"
              :key="opt.value"
              class="checkbox-item"
              :class="{
                'is-checked': (form[item.__vModel__] || []).includes(opt.value),
                'is-disabled': item.disabled || opt.disabled
              }"
              @tap="selectCheckbox(opt.value, item.__vModel__, item.disabled || opt.disabled)"
            >
              <!-- 方形复选框 -->
              <view class="checkbox-icon">
                <view
                  class="checkbox-inner"
                  :class="{ checked: (form[item.__vModel__] || []).includes(opt.value) }"
                ></view>
              </view>
        
              <!-- 文本 -->
              <text class="checkbox-label">{{ opt.label }}</text>
            </label>
          </view>
        </view>

        <!-- 开关 -->
        <switch
          v-else-if="item.type === 'switch'"
          :checked="form[item.__vModel__]"
          v-model="form[item.__vModel__]"
        />

        <!-- 滑块 -->
        <view v-else-if="item.type === 'slider'" style="display: flex; align-items: center;">
          <!-- 滑块 -->
          <slider
            :min="item.min || 0"
            :max="item.max || 100"
            :step="item.step || 1"
            v-model="form[item.__vModel__]"
            @changing="onSliderChanging($event, item.__vModel__)"  
            @change="onSliderChange($event, item.__vModel__)"     
            style="flex: 1;"
          />
          
          <!-- 显示当前值 -->
          <text style="margin-left: 10px; width: 40px; text-align: center;">
            {{ sliderValues[item.__vModel__] || form[item.__vModel__] || 0 }}
          </text>
        </view>
		
		<!-- 时间选择 -->
		<uni-datetime-picker
		  v-if="item.type === 'false'"
		  type="datetime"
		  v-model="form[item.__vModel__]"
		  placeholder="请选择时间"
		  :disabled="item.disabled"
		  :clear-icon="item.clearable"
		  @change="onTimeChange(item.__vModel__, $event)"
		/>
		
		<!-- 时间范围选择（仅时分秒） -->
		<view v-if="item.type === 'false'" class="form-item time-range-item">
		  <label v-if="item.__config__.showLabel !== false" class="form-label">
		    {{ item.__config__.required ? '* ' : '' }}{{ item.__config__.label }}
		  </label>
		  <view class="time-range-container">
		    <!-- 开始时间 -->
		    <uni-datetime-picker
		      type="time"
		      v-model="form[item.__vModel__ + 'Start']"
		      :placeholder="item['start-placeholder'] || '请选择开始时间'"
		      :disabled="item.disabled"
		      :clear-icon="item.clearable"
		      :format="item.format || 'HH:mm:ss'"
		      :value-format="item['value-format'] || 'HH:mm:ss'"
		      @change="onTimeRangeChange(item.__vModel__ + 'Start', $event)"
		    />
		    <text class="separator">{{ item['range-separator'] || '至' }}</text>
		    <!-- 结束时间 -->
		    <uni-datetime-picker
		      type="time"
		      v-model="form[item.__vModel__ + 'End']"
		      :placeholder="item['end-placeholder'] || '请选择结束时间'"
		      :disabled="item.disabled"
		      :clear-icon="item.clearable"
		      :format="item.format || 'HH:mm:ss'"
		      :value-format="item['value-format'] || 'HH:mm:ss'"
		      @change="onTimeRangeChange(item.__vModel__ + 'End', $event)"
		    />
		  </view>
		</view>
		
		<!-- 日期选择器 -->
		<view v-if="item.type === 'date'" class="form-item date-item">
		  <!-- 日期选择组件 -->
		  <uni-datetime-picker
		    type="date"
		    v-model="form[item.__vModel__]"
		    :placeholder="item.placeholder || `请选择${item.__config__.label}`"
		    :disabled="item.disabled"
		    :readonly="item.readonly"
		    :clear-icon="item.clearable"
		    :format="item.format || 'yyyy-MM-dd'"
		    :value-format="item['value-format'] || 'yyyy-MM-dd'"
		    @change="onDateChange(item.__vModel__, $event)"
		  />
		</view>
		
		<!-- 日期范围选择器 -->
		<view v-if="item.type === 'daterange'" class="form-item date-range-item">
		  <!-- 范围选择容器 -->
		  <view class="date-range-container">
		    <!-- 开始日期 -->
		    <uni-datetime-picker
		      type="date"
		      v-model="form[item.__vModel__ + 'Start']"
		      :placeholder="item['start-placeholder'] || '请选择开始日期'"
		      :disabled="item.disabled"
		      :readonly="item.readonly"
		      :clear-icon="item.clearable"
		      :format="item.format || 'yyyy-MM-dd'"
		      :value-format="item['value-format'] || 'yyyy-MM-dd'"
		      @change="onDateRangeChange(item.__vModel__ + 'Start', $event)"
		    />
		    <text class="separator">{{ item['range-separator'] || '至' }}</text>
		    <!-- 结束日期 -->
		    <uni-datetime-picker
		      type="date"
		      v-model="form[item.__vModel__ + 'End']"
		      :placeholder="item['end-placeholder'] || '请选择结束日期'"
		      :disabled="item.disabled"
		      :readonly="item.readonly"
		      :clear-icon="item.clearable"
		      :format="item.format || 'yyyy-MM-dd'"
		      :value-format="item['value-format'] || 'yyyy-MM-dd'"
		      @change="onDateRangeChange(item.__vModel__ + 'End', $event)"
		    />
		  </view>
		</view>




        <!-- 评分 -->
        <!-- 评分组件 -->
        <!-- 评分组件 -->
        <!-- 评分 -->
      <rate-field
        v-if="item.type === 'rate'"
        :item="item"
        :form="form"
      />
	  
	  
	  <!-- 颜色选择组件 -->
	  <view v-if="false" class="form-item color-item">
	    <input
	      type="color"
	      :value="form[item.__vModel__] || '#000000'"  
	      :disabled="item.disabled"
	      @input="onColorChange(item.__vModel__, $event)"
	      class="color-input"
	    />
	  </view>
	  
		</view>
    </scroll-view>

    <button class="submit-btn" @tap="submitForm">提交</button>
  </view>
</template>



<script>
import RateField from '@/components/RateField/RateField.vue'
export default {
  components: { RateField },
  data() {
    return {
      fields: [], // 表单结构
      form: {}, // 用户填写的值
	  editorContexts: {}, // 存储多个编辑器上下文
	  // 临时存储拖动过程中的值（避免影响 form）
	  sliderValues: {},
    }
  },
  onLoad() {
    this.initForm()
  },
  methods: {
    initForm() {
      // 直接写死你提供的 JSON 的 fields 内容
      const data = {"size": "medium", "span": 24, "fields": [{"type": "input", "style": {"width": "100%"}, "__slot__": {"append": "", "prepend": ""}, "disabled": false, "readonly": false, "clearable": true, "maxlength": null, "__config__": {"tag": "el-input", "span": 24, "label": "单行文本", "formId": 101, "layout": "colFormItem", "regList": [], "tagIcon": "input", "document": "https://element.eleme.cn/#/zh-CN/component/input", "required": true, "changeTag": true, "renderKey": "1011709371676616", "showLabel": true, "labelWidth": null}, "__vModel__": "field101", "placeholder": "请输入单行文本单行文本", "prefix-icon": "", "suffix-icon": "", "show-word-limit": false}, {"type": "textarea", "style": {"width": "100%"}, "autosize": {"maxRows": 4, "minRows": 4}, "disabled": false, "readonly": false, "maxlength": null, "__config__": {"tag": "el-input", "span": 24, "label": "多行文本", "formId": 102, "layout": "colFormItem", "regList": [], "tagIcon": "textarea", "document": "https://element.eleme.cn/#/zh-CN/component/input", "required": true, "changeTag": true, "renderKey": "1021709371677509", "showLabel": true, "labelWidth": null}, "__vModel__": "field102", "placeholder": "请输入多行文本", "show-word-limit": false}, {"type": "password", "style": {"width": "100%"}, "__slot__": {"append": "", "prepend": ""}, "disabled": false, "readonly": false, "clearable": true, "maxlength": null, "__config__": {"tag": "el-input", "span": 24, "label": "密码", "formId": 103, "layout": "colFormItem", "regList": [], "tagIcon": "password", "document": "https://element.eleme.cn/#/zh-CN/component/input", "required": true, "changeTag": true, "renderKey": "1031709371678330", "showLabel": true, "labelWidth": null}, "__vModel__": "field103", "placeholder": "请输入密码", "prefix-icon": "", "suffix-icon": "", "show-password": true, "show-word-limit": false}, {"step": 1, "type": "step", "disabled": false, "__config__": {"tag": "el-input-number", "span": 24, "label": "计数器", "formId": 104, "layout": "colFormItem", "regList": [], "tagIcon": "number", "document": "https://element.eleme.cn/#/zh-CN/component/input-number", "required": true, "changeTag": true, "renderKey": "1041709371678707", "showLabel": true, "labelWidth": null}, "__vModel__": "field104", "placeholder": "计数器", "step-strictly": false, "controls-position": ""}, {"type": "editor", "height": 300, "branding": false, "__config__": {"tag": "tinymce", "span": 24, "label": "编辑器", "formId": 105, "layout": "colFormItem", "regList": [], "tagIcon": "rich-text", "document": "http://tinymce.ax-z.cn", "required": true, "changeTag": true, "renderKey": 1709371679402, "showLabel": true, "labelWidth": null, "defaultValue": null}, "__vModel__": "field105", "placeholder": "请输入编辑器"}, {"type": "select", "style": {"width": "100%"}, "__slot__": {"options": [{"label": "选项一", "value": 1}, {"label": "选项二", "value": 2}]}, "disabled": false, "multiple": false, "clearable": true, "__config__": {"tag": "el-select", "span": 24, "label": "下拉选择", "formId": 106, "layout": "colFormItem", "regList": [], "tagIcon": "select", "document": "https://element.eleme.cn/#/zh-CN/component/select", "required": true, "changeTag": true, "renderKey": "1061709371680267", "showLabel": true, "labelWidth": null}, "__vModel__": "field106", "filterable": false, "placeholder": "请选择下拉选择"}, {"size": "medium", "type": "radio", "style": {}, "__slot__": {"options": [{"label": "选项一", "value": 1}, {"label": "选项二", "value": 2}]}, "disabled": false, "__config__": {"tag": "el-radio-group", "span": 24, "label": "单选框组", "border": false, "formId": 108, "layout": "colFormItem", "regList": [], "tagIcon": "radio", "document": "https://element.eleme.cn/#/zh-CN/component/radio", "required": true, "changeTag": true, "renderKey": "1081709371681235", "showLabel": true, "labelWidth": null, "optionType": "default"}, "__vModel__": "field108"}, {"size": "medium", "type": "checkbox", "style": {}, "__slot__": {"options": [{"label": "选项一", "value": 1}, {"label": "选项二", "value": 2}]}, "disabled": false, "__config__": {"tag": "el-checkbox-group", "span": 24, "label": "多选框组", "border": false, "formId": 109, "layout": "colFormItem", "regList": [], "tagIcon": "checkbox", "document": "https://element.eleme.cn/#/zh-CN/component/checkbox", "required": true, "changeTag": true, "renderKey": "1091709371681527", "showLabel": true, "labelWidth": null, "optionType": "default", "defaultValue": []}, "__vModel__": "field109"}, {"type": "switch", "style": {}, "disabled": false, "__config__": {"tag": "el-switch", "span": 24, "label": "开关", "formId": 110, "layout": "colFormItem", "regList": [], "tagIcon": "switch", "document": "https://element.eleme.cn/#/zh-CN/component/switch", "required": true, "changeTag": true, "renderKey": "1101709371682568", "showLabel": true, "labelWidth": null, "defaultValue": false}, "__vModel__": "field110", "active-text": "", "active-color": null, "active-value": true, "inactive-text": "", "inactive-color": null, "inactive-value": false}, {"max": 100, "min": 0, "step": 1, "type": "slider", "range": false, "disabled": false, "__config__": {"tag": "el-slider", "span": 24, "label": "滑块", "formId": 111, "layout": "colFormItem", "regList": [], "tagIcon": "slider", "document": "https://element.eleme.cn/#/zh-CN/component/slider", "required": true, "changeTag": true, "renderKey": "1111709371682889", "showLabel": true, "labelWidth": null, "defaultValue": 0}, "__vModel__": "field111", "show-stops": false}, {"type": "time", "style": {"width": "100%"}, "format": "HH:mm:ss", "disabled": false, "clearable": true, "__config__": {"tag": "el-time-picker", "span": 24, "label": "时间选择", "formId": 112, "layout": "colFormItem", "regList": [], "tagIcon": "time", "document": "https://element.eleme.cn/#/zh-CN/component/time-picker", "required": true, "changeTag": true, "renderKey": "1121709371683416", "showLabel": true, "labelWidth": null, "defaultValue": null}, "__vModel__": "field112", "placeholder": "请选择时间选择", "value-format": "HH:mm:ss", "picker-options": {"selectableRange": "00:00:00-23:59:59"}}, {"type": "timerange", "style": {"width": "100%"}, "format": "HH:mm:ss", "disabled": false, "is-range": true, "clearable": true, "__config__": {"tag": "el-time-picker", "span": 24, "label": "时间范围", "formId": 113, "layout": "colFormItem", "regList": [], "tagIcon": "time-range", "document": "https://element.eleme.cn/#/zh-CN/component/time-picker", "required": true, "changeTag": true, "renderKey": "1131709371683734", "showLabel": true, "labelWidth": null, "defaultValue": null}, "__vModel__": "field113", "value-format": "HH:mm:ss", "end-placeholder": "结束时间", "range-separator": "至", "start-placeholder": "开始时间"}, {"type": "date", "style": {"width": "100%"}, "format": "yyyy-MM-dd", "disabled": false, "readonly": false, "clearable": true, "__config__": {"tag": "el-date-picker", "span": 24, "label": "日期选择", "formId": 114, "layout": "colFormItem", "regList": [], "tagIcon": "date", "document": "https://element.eleme.cn/#/zh-CN/component/date-picker", "required": true, "changeTag": true, "renderKey": "1141709371684329", "showLabel": true, "labelWidth": null, "defaultValue": null}, "__vModel__": "field114", "placeholder": "请选择日期选择", "value-format": "yyyy-MM-dd"}, {"type": "daterange", "style": {"width": "100%"}, "format": "yyyy-MM-dd", "disabled": false, "readonly": false, "clearable": true, "__config__": {"tag": "el-date-picker", "span": 24, "label": "日期范围", "formId": 115, "layout": "colFormItem", "regList": [], "tagIcon": "date-range", "document": "https://element.eleme.cn/#/zh-CN/component/date-picker", "required": true, "changeTag": true, "renderKey": "1151709371684681", "showLabel": true, "labelWidth": null, "defaultValue": null}, "__vModel__": "field115", "value-format": "yyyy-MM-dd", "end-placeholder": "结束日期", "range-separator": "至", "start-placeholder": "开始日期"}, {"max": 5, "type": "rate", "style": {}, "disabled": false, "show-text": false, "__config__": {"tag": "el-rate", "span": 24, "label": "评分", "formId": 116, "layout": "colFormItem", "regList": [], "tagIcon": "rate", "document": "https://element.eleme.cn/#/zh-CN/component/rate", "required": true, "changeTag": true, "renderKey": "1161709371685196", "showLabel": true, "labelWidth": null, "defaultValue": 0}, "__vModel__": "field116", "allow-half": false, "show-score": false}, {"size": "medium", "type": "color", "disabled": false, "__config__": {"tag": "el-color-picker", "span": 24, "label": "颜色选择", "formId": 117, "layout": "colFormItem", "regList": [], "tagIcon": "color", "document": "https://element.eleme.cn/#/zh-CN/component/color-picker", "required": true, "changeTag": true, "renderKey": "1171709371685684", "showLabel": true, "labelWidth": null, "defaultValue": null}, "__vModel__": "field117", "show-alpha": false, "color-format": ""}], "gutter": 15, "formRef": "elForm", "disabled": false, "formBtns": true, "formModel": "formData", "formRules": "rules", "labelWidth": 100, "labelPosition": "right"} // 你也可以直接复制 fields 内容粘贴到这
      this.fields = data.fields

      // 初始化 form 数据
      this.fields.forEach(item => {
		  // 转换 select 的 options 格式
		      if (item.type === 'select') {
		        item.__slot__.options = item.__slot__.options.map(opt => ({
		          text: opt.label,
		          value: opt.value
		        }))
		      }
		  
		  
          const key = item.__vModel__
          const defaultVal = item.__config__.defaultValue
      
          if (item.type === 'checkbox') {
            this.form[key] = Array.isArray(defaultVal) ? defaultVal : []
          } else if (item.type === 'switch') {
            this.form[key] = !!defaultVal
          } 
		  else  if (item.type === 'step') {
        // 计数器：必须是数字
        const config = this.getStepConfig(key)
        const numVal = Number(defaultVal)

        // 如果 defaultValue 有效且在范围内，使用它
        if (!isNaN(numVal) && numVal >= config.min && numVal <= config.max) {
          this.$set(this.form, key, numVal)
        } else {
          // 否则使用 min（用户期望从最小值开始）
          this.$set(this.form, key, config.min)
        }
      }
		  
		  
		  else if (item.type === 'select' && item.__slot__.options?.length) {
  // 🔴 不要自动选第一个
  // 只有当 defaultValue 存在且有效时才设置
  const defaultVal = item.__config__.defaultValue
  if (defaultVal !== null && defaultVal !== undefined) {
    const isValid = item.__slot__.options.some(opt => opt.value === defaultVal)
    this.form[key] = isValid ? defaultVal : null
  } else {
    this.form[key] = null // ✅ 初始化为 null
  }
}
 else if (item.type === 'editor') {
       // ✅ 使用 defaultValue，若为 null 则设为空字符串
       this.form[key] = defaultVal || ''
     }
	 
	 else if (item.type === 'radio') {
	     // ✅ 新增：单独处理 radio 初始化
	     if (defaultVal != null) {
	       const isValid = item.__slot__.options?.some(opt => opt.value === defaultVal)
	       this.form[key] = isValid ? defaultVal : null
	     } else {
	       this.form[key] = null // ✅ 明确初始化为 null，不自动选
	     }
	 
	   } 
	   else if (item.type === 'checkbox') {
    // ✅ 多选框初始化：确保是数组，并验证选项合法性
    if (Array.isArray(defaultVal) && defaultVal.length > 0) {
      // 过滤出存在于 options 中的合法值
      const validOptions = item.__slot__.options?.map(opt => opt.value) || []
      const validDefault = defaultVal.filter(val => validOptions.includes(val))
      
      this.form[key] = validDefault.length > 0 ? validDefault : []
    } else {
      // 默认值不是数组或为空，初始化为 []
      this.form[key] = []
    }
  }
  else if (item.type === 'switch') {
      // 如果 defaultValue 是 true，则设置为 true；否则默认为 false
      const initialValue = defaultVal === true ? true : false;
      this.$set(this.form, key, initialValue)
    }
	else if (item.type === 'slider') {
	      const min = item.min || 0
	      const max = item.max || 100
	      const val = (defaultVal !== undefined && defaultVal >= min && defaultVal <= max)
	        ? defaultVal
	        : min
	
	      this.$set(this.form, key, val)
	      // 可选：初始化临时值
	      this.$set(this.sliderValues, key, val)
	    }
		// 在你的 initForm 逻辑中，添加如下 else if 分支：
		else if (item.type === 'time') {
        const timeRegex = /^([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$/;
        const isValidTime = typeof defaultVal === 'string' && timeRegex.test(defaultVal.trim());
        this.$set(this.form, key, isValidTime ? defaultVal.trim() : '');
      }
	  else if (item.type === 'timerange') {
	        const startKey = key + 'Start';
	        const endKey = key + 'End';
	  
	        // 默认值可能是数组 [start, end] 或 null
	        const defaultVal = item.__config__.defaultValue; // 可能是 null 或 ['09:00:00', '18:00:00']
	  
	        let startValue = '';
	        let endValue = '';
	  
	        if (Array.isArray(defaultVal) && defaultVal.length === 2) {
	          const timeRegex = /^([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$/;
	          if (timeRegex.test(defaultVal[0])) startValue = defaultVal[0];
	          if (timeRegex.test(defaultVal[1])) endValue = defaultVal[1];
	        }
	  
	        // 初始化 form
	        this.$set(this.form, startKey, startValue);
	        this.$set(this.form, endKey, endValue);
	      }
		  else if (item.type === 'date') {
      // 验证默认值是否为合法的日期字符串（yyyy-MM-dd）
      const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
      const isValidDate = typeof defaultVal === 'string' && dateRegex.test(defaultVal.trim());

      // 初始化 form
      this.$set(this.form, key, isValidDate ? defaultVal.trim() : '');
    }
	else if (item.type === 'daterange') {
      const startKey = key + 'Start';
      const endKey = key + 'End';

      // 默认值可能是数组 [start, end] 或 null
      const defaultVal = item.__config__.defaultValue; // 如 ["2025-04-01", "2025-04-30"]

      let startValue = '';
      let endValue = '';

      if (Array.isArray(defaultVal) && defaultVal.length === 2) {
        const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
        if (dateRegex.test(defaultVal[0])) startValue = defaultVal[0];
        if (dateRegex.test(defaultVal[1])) endValue = defaultVal[1];
      }

      // 初始化 form
      this.$set(this.form, startKey, startValue);
      this.$set(this.form, endKey, endValue);
    }
	else if (item.type === 'rate') {
	  const defaultVal = item.__config__.defaultValue
	  const isValidNumber = typeof defaultVal === 'number' && defaultVal >= 0
	  this.$set(this.form, key, isValidNumber ? defaultVal : 0)
	}
	else if (item.type === 'color') {
      // 默认值优先，否则设为黑色（input[type=color] 不能为空）
      const defaultValue = item.__config__.defaultValue || '#000000';
      this.$set(this.form, key, defaultValue);
    }
 else {
            this.form[key] = defaultVal !== null && defaultVal !== undefined ? defaultVal : ''
          }
        })
      
        console.log('form 初始化完成:', this.form)
    },
    onSelectChange(value, modelKey) {
        console.log(`字段 ${modelKey} 已选择:`, value);
        // 可在此添加联动逻辑、表单验证等
      },
	  // 选择单选框
	    selectRadio(value, field, disabled) {
	      console.log("点击选项，值:", value, "字段:", field)
	      if (disabled) return;
	    
	      this.$set(this.form, field, value)
	    
	      // 🔥 关键：强制 Vue 知道 form 变了
	      this.form = { ...this.form } // ✅ 强制刷新（临时方案）
	    
	      console.log("当前 form:", this.form)
	      this.$emit('input', { [field]: value })
	    },
		//选择多选框
    selectCheckbox(value, field, disabled) {
        if (disabled) return;
    
        // 确保 form[field] 是数组
        const current = this.form[field] || [];
        const index = current.indexOf(value);
        let newValue = [...current];
    
        if (index > -1) {
          // 已选中，取消
          newValue.splice(index, 1);
        } else {
          // 未选中，添加
          newValue.push(value);
        }
    
        // 使用 $set 确保响应式
        this.$set(this.form, field, newValue);
    
        // 可选：强制刷新（uni-app 小程序更稳）
        this.form = { ...this.form };
    
        // 触发 input 事件（用于 v-model）
        this.$emit('input', { [field]: newValue });
      },
	//滑块拖动
	  // 拖动过程中（实时）
	    onSliderChanging(e, key) {
	      const value = e.detail.value
	      // 存入临时对象，用于界面显示
	      this.$set(this.sliderValues, key, value)
	    },
	  
	    // 拖动结束（最终确认值）
	    onSliderChange(e, key) {
	      const value = e.detail.value
	      // 更新到 form（v-model 已绑定，这步其实可省略，但更明确）
	      this.$set(this.form, key, value)
	      // 清除临时值（可选）
	      this.$delete(this.sliderValues, key)
	    },
		
		
		// 时间选择 change 事件
		  onTimeChange(key, value) {
		    // key: 字段的 __vModel__，如 'field112'
		    // value: 选择的时间字符串，如 '14:30:25'
		
		    console.log('[TimePicker] change event:', { key, value })
		
		    // 1. ✅ 确保更新 form 值（uni-datetime-picker 已经返回字符串）
		    //    但使用 $set 保证响应式
		    this.$set(this.form, key, value)
		
		    // 2. 🔍 可选：添加自定义逻辑，例如
		    //    - 表单校验
		    //    - 字段联动（比如结束时间不能早于开始时间）
		    //    - 发送埋点
		    //    - 触发父组件事件
		
		    // 示例：简单校验（非空）
		    if (!value) {
		      console.warn(`[警告] 时间字段 ${key} 为空`)
		      // 可以触发提示
		      // uni.showToast({ title: '时间不能为空', icon: 'none' })
		    }
		
		    // 示例：触发父组件监听（如果你需要）
		    // this.$emit('field-change', { field: key, value, type: 'time' })
		
		    // 3. ✅ 可选：如果你有表单验证模块，可以在这里触发验证
		    // this.validateField(key)
		  },
		  
		  onDateTimeRangeChange(key, value) {
		      console.log('[DateTimeRange] change event:', { key, value });
		  
		      // 更新 form 值
		      this.$set(this.form, key, value);
		  
		      // 获取对应的开始/结束字段名
		      const isStart = key.endsWith('Start');
		      const baseKey = key.replace(/(Start|End)$/, ''); // 提取基础 key
		      const startKey = baseKey + 'Start';
		      const endKey = baseKey + 'End';
		  
		      const startTime = this.form[startKey];
		      const endTime = this.form[endKey];
		  
		      // 只有当两个时间都存在时才校验
		      if (startTime && endTime) {
		        // 将字符串转为 Date 对象比较
		        const start = new Date(startTime);
		        const end = new Date(endTime);
		  
		        if (end <= start) {
		          // 结束时间不能小于等于开始时间
		          this.$set(this.form, endKey, ''); // 清空结束时间
		          uni.showToast({
		            title: '结束时间必须晚于开始时间',
		            icon: 'none',
		            duration: 2000
		          });
		        }
		      }
		    },
			onDateChange(key, value) {
			    console.log('[DatePicker] change event:', { key, value });
			
			    // 更新 form 值
			    this.$set(this.form, key, value);
			
			    // 可选：添加自定义逻辑，比如联动、校验等
			    if (!value) {
			      console.warn(`[警告] 日期字段 ${key} 已清空`);
			    }
			  },
			  onDateRangeChange(key, value) {
			      console.log('[DateRangePicker] change event:', { key, value });
			  
			      // 更新 form 值
			      this.$set(this.form, key, value);
			  
			      // 提取基础 key（如 field115）
			      const baseKey = key.replace(/(Start|End)$/, '');
			      const startKey = baseKey + 'Start';
			      const endKey = baseKey + 'End';
			  
			      const startDate = this.form[startKey];
			      const endDate = this.form[endKey];
			  
			      // 只有当两个日期都存在时才校验
			      if (startDate && endDate) {
			        // 字符串比较（yyyy-MM-dd 格式可直接比较）
			        if (endDate <= startDate) {
			          this.$set(this.form, endKey, ''); // 清空结束日期
			          uni.showToast({
			            title: '结束日期必须晚于开始日期',
			            icon: 'none',
			            duration: 2000
			          });
			        }
			      }
			    },
				onRateChange(field, value) {
				  // 直接赋值数字
				  this.$set(this.form, field, value)
				  console.log(`评分字段 ${field} 变化:`, value)
				},
				onColorChange(key, event) {
				    const color = event.detail.value; // 获取颜色值，如 #ff0000
				    this.$set(this.form, key, color);
				    console.log(`颜色更新: ${key} = ${color}`);
				  },
		
    submitForm() {
      console.log('提交数据：', this.form)
      uni.showToast({
        title: '提交成功',
        icon: 'success'
      })
    },
	
	getStepConfig(key) {
	  const field = this.fields.find(f => f.__vModel__ === key);
	  return {
	    step: field.step || 1,
	    min: field.min || 0,
	    max: field.max || 999999,
	  };
	},
	
	increaseStep(key) {
	  const { step, max } = this.getStepConfig(key);
	  let val = Number(this.form[key]) || 0;
	  val += step;
	  if (val > max) val = max;
	  this.$set(this.form, key, val);
	},
	decreaseStep(key) {
	  const { step, min } = this.getStepConfig(key);
	  let val = Number(this.form[key]) || 0;
	  val -= step;
	  if (val < min) val = min;
	  this.$set(this.form, key, val);
	},
	isStepMin(key) {
	  const { min } = this.getStepConfig(key);
	  return this.form[key] <= min;
	},
	isStepMax(key) {
	  const { max } = this.getStepConfig(key);
	  return this.form[key] >= max;
	},
	onStepInput(key, e) {
	  const { min, max } = this.getStepConfig(key);
	  let val = Number(e.detail.value);
	  if (isNaN(val)) val = min;
	  if (val < min) val = min;
	  if (val > max) val = max;
	  this.$set(this.form, key, val);
	},
	// 编辑器准备就绪
	  onEditorReady(event, fieldKey) {
	    const editorId = 'editor-' + fieldKey
	    uni.createSelectorQuery().in(this)
	      .select('#' + editorId)
	      .context(res => {
	        this.editorContexts[fieldKey] = res.context
	      })
	      .exec()
	  },
	
	  // 内容变化：更新 form 数据
	  onEditorInput(event, fieldKey) {
	    // 优先用 HTML，降级用 text
	    const content = event.detail.html || event.detail.text || ''
	    this.form[fieldKey] = content
	  },
	
	  onEditorFocus(event) {
	    console.log('Editor Focus:', event)
	  },
	
	  onEditorBlur(event) {
	    console.log('Editor Blur:', event)
	  }
  }
}
</script>

<style>
.container {
  padding: 20rpx;
}
.form-scroll {
  height: 100vh;
}
.form-item {
  margin-bottom: 30rpx;
}
.label {
  font-weight: bold;
  margin-bottom: 10rpx;
}

/* 单行文本框 */
.uni-input {
  font-size: 14px;
  line-height: 1.5;
  height: 36px;             /* 固定高度，跟文本域起始高度差不多 */
  padding: 0 12px;          /* 左右内边距 */
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
  width: 100%;
  transition: border-color 0.2s ease, box-shadow 0.2s ease;
}

.uni-input:focus {
  border-color: #409eff;
  outline: none;
  box-shadow: 0 0 5px rgba(64, 158, 255, 0.5);
}

/*多行文本框 */
.uni-textarea {
  font-size: 14px;       /* 跟单行输入字体大小一致 */
  line-height: 1.5;      /* 行高更舒服 */
  min-height: 80px;      /* 最小高度 */
  max-height: 160px;     /* 最大高度，避免撑得太高 */
  padding: 8px 12px;     /* 内边距稍微多一点 */
  border: 1px solid #ccc; /* 边框样式 */
  border-radius: 4px;     /* 圆角 */
  resize: vertical;       /* 允许用户垂直调整大小 */
  box-sizing: border-box; /* 让内边距不影响整体宽度 */
  width: 100%;            /* 充满父元素宽度 */
  transition: border-color 0.2s ease;
}

.uni-textarea:focus {
  border-color: #409eff;  /* 焦点时边框颜色高亮 */
  outline: none;
}

/* 计数器 */
.uni-input-number {
  display: flex;
  align-items: center;
}

.btn-decrease, .btn-increase {
  width: 40px;
  height: 40px;
  background-color: #f8f8f8;
  border: 1px solid #ddd;
  border-radius: 3px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
  margin: 0 5px;
}

.btn-decrease:hover, .btn-increase:hover {
  background-color: #e8e8e8;
}

.btn-decrease:disabled, .btn-increase:disabled {
  background-color: #eee;
  cursor: not-allowed;
}

.input-number {
  width: 60px;
  height: 40px;
  margin: 0 5px;
  text-align: center;
  border: 1px solid #ddd;
  border-radius: 3px;
  font-size: 16px;
  padding: 0;
}



/* 下拉选择整体样式 */
.form-item-select {
  width: 100%;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 14px;
  color: #333;
}

/* 选中区域的样式（uni-data-select 内部类名） */
.form-item-select .uni-select__text {
  padding: 10px 12px;
  min-height: 40px;
  line-height: 20px;
}

.form-item-select .uni-select__input-text {
  font-size: 14px;
}

/* 占位符颜色 */
.form-item-select .uni-placeholder {
  color: #aaa;
}

/* 边框高亮（聚焦/点击） */
.form-item-select .uni-select--border {
  border-color: #007aff;
}

/* 弹出层样式优化 */
.select-popup .uni-select__popover {
  border-radius: 12px !important;
}

.select-popup .uni-select__list-item {
  font-size: 16px;
  padding: 12px 16px;
}

/* 富文本编辑器 */
.form-item-editor {
  border: 1px solid #ddd;
  border-radius: 6px;
  overflow: hidden;
  background-color: #fff;
  position: relative;
}

.form-item-editor editor {
  min-height: 300px;
  font-size: 14px;
  line-height: 1.5;
  padding: 10px;
  box-sizing: border-box;
}

/* H5 平台兼容 */
/* #ifdef H5 */
.form-item-editor >>> .uni-rich-text {
  min-height: 300px;
  max-height: 300px;
}
.form-item-editor >>> .uni-rich-text-editor {
  min-height: 300px;
  max-height: 300px;
}
/* #endif */


/* 单选框组容器 */
.radio-group {
  display: flex;
  flex-direction: column;
  margin-bottom: 15px;
}

/* 标签样式 */
.radio-group__label {
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
  font-weight: 500;
}

/* 选项容器 */
.radio-options {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

/* 水平排列 */
.radio-group--horizontal .radio-options {
  flex-direction: row;
  flex-wrap: wrap;
  gap: 15px;
}

/* 单个选项 */
.radio-item {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #666;
  padding: 6px 0;
  cursor: pointer;
}

.radio-item.is-disabled {
  color: #ccc;
  opacity: 0.7;
  pointer-events: none;
}

/* 自定义单选图标 */
.radio-icon {
  position: relative;
  width: 18px;
  height: 18px;
  border: 1px solid #999;
  border-radius: 50%;
  margin-right: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.radio-inner {
  width: 6px;
  height: 6px;
  background-color: #fff;
  border-radius: 50%;
  transition: all 0.2s;
}

.radio-inner-checked {
  position: absolute;
  width: 10px;
  height: 10px;
  background-color: #007AFF;
  border-radius: 50%;
  box-shadow: 0 0 0 2px #fff;
}

/* 选中状态 */
.radio-item.is-checked .radio-icon {
  border-color: #007AFF;
}

.radio-item.is-checked .radio-inner {
  background-color: #007AFF;
}



/* 多选框组容器 */
.checkbox-group {
  display: flex;
  flex-direction: column;
  margin-bottom: 15px;
}

/* 标签样式 */
.checkbox-group__label {
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
  font-weight: 500;
}

/* 选项容器 */
.checkbox-options {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

/* 水平排列 */
.checkbox-group--horizontal .checkbox-options {
  flex-direction: row;
  flex-wrap: wrap;
  gap: 15px;
}

/* 单个选项 */
.checkbox-item {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #666;
  padding: 6px 0;
  cursor: pointer;
}

.checkbox-item.is-disabled {
  color: #ccc;
  opacity: 0.7;
  pointer-events: none;
}

/* 自定义复选框图标 */
.checkbox-icon {
  position: relative;
  width: 18px;
  height: 18px;
  border: 1px solid #999;
  border-radius: 4px;
  margin-right: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 内部方块 */
.checkbox-inner {
  width: 8px;
  height: 8px;
  background-color: #fff;
  border-radius: 2px;
  transition: all 0.2s;
}

/* 选中状态 */
.checkbox-item.is-checked .checkbox-icon {
  border-color: #007AFF;
  background-color: #007AFF;
}

.checkbox-item.is-checked .checkbox-inner {
  background-color: #fff;
  width: 10px;
  height: 10px;
  transform: rotate(45deg);
  border: 2px solid #fff;
  border-top: 0;
  border-left: 0;
}
.star {
  display: inline-block;
  font-size: 50rpx;
  padding: 0 10rpx;
}
.active-star {
  color: #FFD700;
}
.inactive-star {
  color: #ccc;
}
.submit-btn {
  margin-top: 30rpx;
  background-color: #007AFF;
  color: #fff;
}


.color-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.form-label {
  font-weight: bold;
  margin-right: 10px;
  color: #333;
  font-size: 14px;
  width: 80px;
  text-align: right;
}

.color-input {
  width: 60px;
  height: 40px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  /* 隐藏默认边框和箭头 */
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  outline: none;
}

/* 去掉 input[type=color] 的默认样式边框 */
.color-input::-webkit-color-swatch-wrapper {
  padding: 0;
}
.color-input::-webkit-color-swatch {
  border: none !important;
  border-radius: 4px;
}


</style>
